#ifndef NJF_RASTER_RECTS_H
#define NJF_RASTER_RECTS_H

/* simple sanity check */
BEST_INLINE int RectSanityCheck(const RasterRect *rect)
{
    return (rect->w > 0 && rect->h > 0);
}

BEST_INLINE void ClipRect(const RasterRect *clip, RasterRect *dst)
{
    int dw, dh;
    if(dst->x < clip->x)
    {
        int dx = (clip->x - dst->x);
        dst->x += dx;
        dst->w -= dx;
    }
    if(dst->y < clip->y)
    {
        int dy = (clip->y - dst->y);
        dst->y += dy;
        dst->h -= dy;
    }
    dw = (clip->x + clip->w) - dst->x;
    if(dw < dst->w)
    {
        dst->w = dw;
    }
    dh = (clip->y + clip->h) - dst->y;
    if(dh < dst->h)
    {
        dst->h = dh;
    }
}

BEST_INLINE void ClipBlitRects(const RasterRect* clip, RasterRect *dst, RasterRect *src)
{
    Fixed spx = IntToFixed(src->w) / dst->w;
    Fixed spy = IntToFixed(src->h) / dst->h;
    int dw, dh;
    if(dst->x < clip->x)
    {
        int dx = (clip->x - dst->x);
        Fixed sdx = dx * spx;
        dst->x += dx;
        dst->w -= dx;
        src->x += FixedToInt(sdx);
        src->w -= FixedToInt(sdx);
    }
    if(dst->y < clip->y)
    {
        int dy = (clip->y - dst->y);
        Fixed sdy = dy * spy;
        dst->y += dy;
        dst->h -= dy;
        src->y += FixedToInt(sdy);
        src->h -= FixedToInt(sdy);
    }
    dw = (clip->x + clip->w) - dst->x;
    if(dw < dst->w)
    {
        dst->w = dw;
        src->w = FixedToInt(dw * spx);
    }
    dh = (clip->y + clip->h) - dst->y;
    if(dh < dst->h)
    {
        dst->h = dh;
        src->h = FixedToInt(dh * spy);
    }
}

#endif /* NJF_RASTER_RECTS_H */
